<template>
    <div class="main">
        <el-card style="width:500px; height:300px">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="用户名称" prop="LoginName">
        <el-input v-model="ruleForm.LoginName" />
      </el-form-item>
      <el-form-item label="用户密码" prop="LoginPwd">
        <el-input type="password" v-model="ruleForm.LoginPwd" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
</el-card>
</div>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
  import axios from 'axios'
  import { useRouter } from 'vue-router'
  import {  useCounterStore } from '../../stores/counter.ts'

  const router=useRouter()
  const store=useCounterStore();
  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive({
    LoginName: '',
    LoginPwd: '',
  })
  
  const rules = reactive<FormRules>({
    LoginName: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
    ],
    LoginPwd: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
    ],
  })
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('submit!')
        axios.get("/api/Login/Login?uname="+ruleForm.LoginName+'&pwd='+ruleForm.LoginPwd)
        .then(res=>{
            if(res.data.Data.Code==1){
                ElMessage.success(res.data.Data.Message)

                //本地保存 JWT
                window.localStorage.setItem("token",res.data.Data.UserJWT)

                //后续数据提交需加入JWT ToKen令牌
                axios.defaults.headers.common['Authorization']='Bearer '+res.data.Data.UserJWT;


                //保存用户信息
                store.uName=res.data.Data.LogingName
                store.IsLogin=true

                //跳转到主页面
                router.push("/HomeTotel")
            }else{
              ElMessage.error(res.data.Data.Message)
            }
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
  }))
  </script>


<style>
.main {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
  